package com.asking.service.recommended;

import com.asking.dao.CategoryMapper;
import com.asking.dao.QuestionMapper;
import com.asking.dao.RecommendMapper;
import com.asking.domain.Category;
import com.asking.domain.History;
import com.asking.domain.Question;
import com.asking.pojo.EsQuestion;
import com.asking.service.es.QuestionRepository;
import com.asking.vo.ResultVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
import org.apache.mahout.cf.taste.similarity.precompute.example.GroupLensDataModel;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 推荐
 *
 * @Author: 郭旭
 */
@Service
@Transactional
public class RecommendService {

    @Resource
    private RecommendMapper recommendMapper;
    @Resource
    private CategoryMapper categoryMapper;

    public void history() throws IOException {
        List<History> histories = recommendMapper.selectAll();
        BufferedWriter bw = new BufferedWriter(new FileWriter("ratings.dat"));
        for (History history : histories) {
            bw.write(history.getUid() + "::" + history.getQid() + "::" + history.getScore() + "::" + history.getHistoryTime().getTime());
            bw.newLine();
            bw.flush();
        }
        //释放资源
        bw.close();
    }

    /**
     * 协同算法推荐
     *
     * @param userId
     * @param itemId
     * @param many
     * @return
     * @throws Exception
     */
    public List<RecommendedItem> history(Integer userId, Integer itemId, Integer many) throws Exception {
        DataModel dataModel = new GroupLensDataModel(new File("E:\\Code\\superQuestion\\asking-parent\\ratings.dat"));
        ItemSimilarity itemSimilarity = new PearsonCorrelationSimilarity(dataModel);
        //构建推荐器，协同过滤推荐有两种，分别是基于用户的和基于问题的，这里使用基于物品的协同过滤推荐
        GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity);
        //给用户推荐若干个相似的问题
        List<RecommendedItem> recommendedItems = recommender.recommendedBecause(userId, itemId, many);
        return recommendedItems;
    }

    /**
     * 分类推荐
     *
     * @param userId
     * @return
     */
    public List<History> categoryHistory(String userId) {
        List<Category> categories = categoryMapper.selectAll();
        List<History> list = new ArrayList<>();
        for (Category category : categories) {
            List<History> histories = recommendMapper.historyCategory(Integer.parseInt(userId), category.getId());
            list.add(histories.get(0));
        }
        return list;
    }

    @Resource
    private QuestionRepository questionRepository;

    /**
     * 根据分类推荐
     *
     * @param cname
     * @return
     */
    public List<EsQuestion> byCategory(String cname) {
        NativeSearchQueryBuilder queryBuilders = new NativeSearchQueryBuilder();
        queryBuilders.withQuery(QueryBuilders.matchQuery("type", cname));
        queryBuilders.withSort(SortBuilders.fieldSort("lastUpdateTime").order(SortOrder.DESC));
        Page<EsQuestion> search = questionRepository.search(queryBuilders.build());
        return search.getContent();
    }


   /* public List<EsQuestion> byUserHobby(String hobby) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.matchQuery("type",hobby));
        queryBuilder.withSort(SortBuilders.fieldSort("lastUpdateTime").order(SortOrder.DESC));
        Page<EsQuestion> search = questionRepository.search(queryBuilder.build());
        return   search.getContent();
    }*/
     @Resource
     private  QuestionMapper  questionMapper;
    public ResultVo  questionHot(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        List<Question> hot = questionMapper.findHot();
        PageInfo<Question>  info=new PageInfo<>(hot);
        ResultVo  resultVo=new ResultVo();
        resultVo.setTotal(info.getTotal());
        resultVo.setRows(info.getList());
        return resultVo;
    }


}
